import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'dart:ui';


import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:wis_flutter/index.dart';        // wis flutter 组件 
import 'package:photo_view/photo_view.dart';


// 图片上传
class UploadPicturesPage extends StatefulWidget {

    final dynamic controller;      // 表单名称
    final String label;           // lable
    final bool validator;         // 校验
    final String validatorText;   // 校验提示
    final bool readOnly;          // 只读
    final dynamic onChanged;    // 值改变
    final dynamic onDeleteChildren;    // children 图片回调
    final List children;   // 自定义图片
    final double maxLimit; // 数量限制
    final bool  hideAddButton; // 隐藏添加按钮
    final bool hideCameraButton; // 隐藏相机按钮


    UploadPicturesPage({
        Key key,
        this.controller,
        this.label,
        this.validator=false,
        this.validatorText="必填",
        this.readOnly=false,   
        this.onChanged,
        this.onDeleteChildren,
        this.children,
        this.maxLimit=0,
        this.hideAddButton=false,
        this.hideCameraButton=false,


        
    }) : super(key: key);  

    @override
    _UploadPicturesPageState createState() => new _UploadPicturesPageState();
}

class _UploadPicturesPageState extends State<UploadPicturesPage> {

    List<File> _imageList=[];       // 图片 box
    final picker = ImagePicker();

    OverlayEntry overlayEntry;
    LayerLink layerLink = new LayerLink();

    // 初始化
    void initState() {
      super.initState();  

      this._setForm(); // 设置表单
    }

    @override
    void dispose() {
      super.dispose();
    }

    // 保存时间
    void _saveFunc(){

      // 回调
      if( widget.onChanged!=null ){
        widget.onChanged(_imageList); 
      } 

      this._setForm(); // 设置表单
    }

    // 设置表单
    void _setForm(){
      var len=(_imageList.length)+ ( (widget.children!=null)?widget.children.length:0);
      widget.controller.text= len>0?jsonEncode(len):'';
    }

    // 删除
    void _deleteFunc(i){

      List<File> _newList=[];

      // for(var o in _imageList ){
      for (var j = 0; j < _imageList.length; j++) {
        if( j!=i ){
          _newList.add(_imageList[j]);
        }
      }
      
      setState(() {
        _imageList=_newList;
      });      
      
      this._saveFunc(); // 保存
    }


    // 数量 限制
    bool _maxLimitFunc(){

      if( widget.maxLimit>0 ){
        if( ( ( (widget.children!=null)?widget.children.length:0) ) > widget.maxLimit ) {
        // if( ( ( (widget.children!=null)?widget.children.length:0)+_imageList.length ) > widget.maxLimit ) {
          WisMessageGlobal.warning(
            context:context,
            title:"已达上限！",   
            content: '最多上传文件数量为【${widget.maxLimit.floor().toString()}】'
          );
          return true;
        }
      }

      return false;


    }

    // 拍照
    Future _photoImage(context) async {

      final pickedFile = await picker.getImage(source: ImageSource.camera); 

      // 未选择
      if( pickedFile==null ) return;

      // 限制 数量
      if( this._maxLimitFunc() ) return;

      _imageList.add(File(pickedFile.path));


      this._saveFunc(); 

      setState(() {
      });     
   
    }


    //相册选择
    Future _getImageFromGallery(context) async {
      var image = await picker.getImage(source: ImageSource.gallery);

      // 未选择
      if( image==null ) return;

      // 限制 数量
      if( this._maxLimitFunc() ) return;

      _imageList.add(File(image.path));


      this._saveFunc(); 

      setState(() {
      });

    }



    // 预览图片
    void _previewImg(option,isImg){
      overlayEntry = createSelectPopupWindow(option,isImg);
      Overlay.of(context).insert(overlayEntry);
      FocusScope.of(context).requestFocus(FocusNode());
    }



    // 创建 弹框
    OverlayEntry createSelectPopupWindow(option,isImg) {
      OverlayEntry overlayEntry = OverlayEntry(builder: (context) {

        final size =MediaQuery.of(context).size;

        return Positioned(
          width: size.width,
          height: size.height,
          child: CompositedTransformFollower(
            offset: Offset(0.0, 50),
            link: layerLink,
            child: Material(
              child: Stack(
                children: <Widget>[

                  PhotoView(
                    imageProvider: isImg ? 
                      NetworkImage(option["image"])
                      :
                      FileImage(_imageList[option] ) 
                  ),


                  Positioned(
                    top: 55.0,
                    right: 15.0,  
                    child:  IconButton(
                      onPressed: (){
                        this._removeOverlayEntry();
                      },
                      tooltip: '关闭',
                      icon: Icon(Icons.close ),
                      color: Colors.white,
                    )               
                  ), 

                ],
              )
            ),
          ),
        );
      });
      return overlayEntry;
    }


    // 关闭弹框
    void _removeOverlayEntry(){
      overlayEntry.remove();
    }


    // 遍历 自定义图片  
    Widget _bodyInit(context) {

        List<Widget> _list = [];

        // Widget content; 
        for(var o in widget.children ) {
          _list.add(
            Padding(
              padding: EdgeInsets.fromLTRB(6,6,6,6),
              child: Container(
                child: Stack(
                  children: <Widget>[
                    CachedNetworkImage(             
                      imageUrl: o["image"],
                      width: 70,
                      height: 70,    
                      fit: BoxFit.cover,
                      placeholder: (context, url) => CircularProgressIndicator(),
                      errorWidget: (context, url, error) => Column(
                        children: <Widget>[
                          Container(
                            width: 70,
                            height: 70, 
                            child: Icon( 
                              Icons.error,
                              color: Colors.black54, 
                            ),
                          )

                        ],
                      ),
                    ),
                    // Image.network(
                    //   o["image"],
                    //   width: 70,
                    //   height: 70,
                    //   fit: BoxFit.cover
                    // ),

                    Container(
                      margin: EdgeInsets.fromLTRB(0,22,0,0),
                      width: 24,
                      height: 24,
                      child: !widget.readOnly ? IconButton(
                        icon: Icon(Icons.close),
                        onPressed: (){
                          if( widget.onDeleteChildren!=null ){
                            widget.onDeleteChildren(o);
                          }
                        },
                        tooltip: '删除',
                        color: Colors.redAccent,
                        // backgroundColor: Colors.redAccent,
                      ): Text(""),
                    ),


                    Container(
                      margin: widget.readOnly ? EdgeInsets.fromLTRB(16,22,0,0):EdgeInsets.fromLTRB(32,22,0,0),
                      width: 24,
                      height: 24,
                      child:  IconButton(
                        icon: Icon(Icons.remove_red_eye ),
                        onPressed: (){
                          this._previewImg(o,true);
                        },
                        color: Colors.blue,
                      ),
                    ),

                  ]
                )
              )
            ),
          );
        }


        return Wrap(
          children:_list.toList()
        );
    }


    // 遍历 上传图片
    Widget _bodyUploading(context) {

        List<Widget> _list = [];

        // 暂时 隐藏 不显示
        // for (var i = 0; i < _imageList.length; i++) {
        //    var o=_imageList[i];   
        //   _list.add(
        //     Padding(
        //       padding: EdgeInsets.fromLTRB(6,6,6,6),
        //       child: Container(
        //         child: Stack(
        //           children: <Widget>[
        //             Image.file(
        //               o,
        //               width: 70,
        //               height: 70,
        //               fit: BoxFit.cover
        //             ),
        //             Container(
        //               margin: EdgeInsets.fromLTRB(0,22,0,0),
        //               width: 24,
        //               height: 24,
        //               child:  IconButton(
        //                 icon: Icon(Icons.close),
        //                 onPressed: (){
        //                   this._deleteFunc(i);
        //                 },
        //                 tooltip: '删除',
        //                 color: Colors.redAccent,
        //               ),
        //             ),

        //             Container(
        //               margin: EdgeInsets.fromLTRB(32,22,0,0),
        //               width: 24,
        //               height: 24,
        //               child:  IconButton(
        //                 icon: Icon(Icons.remove_red_eye ),
        //                 onPressed: (){
        //                   this._previewImg(i,false);
        //                 },
        //                 tooltip: '预览', 
        //                 color: Colors.blue
        //               ),
        //             ),


        //           ],
        //         ),
        //       )
        //     ),
        //   );
        // }


        return Wrap(
          children:_list.toList()
        );
    }


    @override
    Widget build(BuildContext context) {
        return Padding(
          padding: EdgeInsets.fromLTRB(16,32,16,16),
          child:  Container(
            // color: Colors.white,
            child: Stack(
                children: <Widget>[

                  Container(
                    child: !widget.readOnly ? Container(
                        margin: EdgeInsets.fromLTRB(0,38,0,0),
                        child: Row(
                          children: <Widget>[
                            Container(
                              margin: !widget.hideAddButton ? EdgeInsets.fromLTRB(8,0,16,0):EdgeInsets.fromLTRB(0,0,0,0),
                              child: !widget.hideAddButton ? Ink(
                                decoration: const ShapeDecoration(
                                  color: Colors.lightBlue,
                                  shape: CircleBorder(),
                                ),
                                child: IconButton(
                                  onPressed: (){
                                    this._getImageFromGallery(context);
                                  },
                                  tooltip: '相册',
                                  icon: Icon(Icons.add),
                                  color: Colors.white,
                                )
                              ) : Text(" "),
                            ),
                            Container(
                              margin: EdgeInsets.fromLTRB(0,0,0,0),
                              child: !widget.hideCameraButton ? Ink(
                                decoration: const ShapeDecoration(
                                  color: Colors.lightBlue,
                                  shape: CircleBorder(),
                                ),
                                child: IconButton(
                                  onPressed: (){
                                    this._photoImage(context);
                                  },
                                  tooltip: '拍照',
                                  icon: Icon(Icons.add_a_photo),
                                  color: Colors.white,
                                )
                              ):Text(" "),
                            ),
                          ],
                        )
                      ):Text(""),
                  ),

                  Container(
                    // padding: EdgeInsets.fromLTRB(0,0,0,16),
                    child: Row(
                      children: <Widget>[

                        Text(
                          widget.validator?'*':'',
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.red
                          )
                        ),  

                        Text(
                          widget.label.toString(),
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 14,
                              color: const Color.fromRGBO(81,90,110,1)
                          ),
                        )
                      ],
                    ),
                  ),

                  Container(
                    margin: !widget.readOnly ? EdgeInsets.fromLTRB(0,92,0,0) : EdgeInsets.fromLTRB(0,38,0,0),
                    // color: Colors.red,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[

                        // this._bodyInit(context),       // 自定义图片
                        // this._bodyUploading(context),  // 上传

                        Wrap(
                          children: widget.children.map((o) {
                            return Padding(
                              padding: EdgeInsets.fromLTRB(6,6,6,6),
                              child: Container(
                                child: Stack(
                                  children: <Widget>[
                                    CachedNetworkImage(             
                                      imageUrl: o["image"],
                                      width: 70,
                                      height: 70,    
                                      fit: BoxFit.cover,
                                      placeholder: (context, url) => CircularProgressIndicator(),
                                      errorWidget: (context, url, error) => Column(
                                        children: <Widget>[
                                          Container(
                                            width: 70,
                                            height: 70, 
                                            child: Icon( 
                                              Icons.error,
                                              color: Colors.black54, 
                                            ),
                                          )

                                        ],
                                      ),
                                    ),
                                    // Image.network(
                                    //   o["image"],
                                    //   width: 70,
                                    //   height: 70,
                                    //   fit: BoxFit.cover
                                    // ),

                                    Container(
                                      margin: EdgeInsets.fromLTRB(0,22,0,0),
                                      width: 24,
                                      height: 24,
                                      child: !widget.readOnly ? IconButton(
                                        icon: Icon(Icons.close),
                                        onPressed: (){
                                          if( widget.onDeleteChildren!=null ){
                                            widget.onDeleteChildren(o);
                                          }
                                        },
                                        tooltip: '删除',
                                        color: Colors.redAccent,
                                        // backgroundColor: Colors.redAccent,
                                      ): Text(""),
                                    ),


                                    Container(
                                      margin: widget.readOnly ? EdgeInsets.fromLTRB(16,22,0,0):EdgeInsets.fromLTRB(32,22,0,0),
                                      width: 24,
                                      height: 24,
                                      child:  IconButton(
                                        icon: Icon(Icons.remove_red_eye ),
                                        onPressed: (){
                                          this._previewImg(o,true);
                                        },
                                        color: Colors.blue,
                                      ),
                                    ),

                                  ]
                                )
                              )
                            );
                          }).toList()
                        ),
 
                        Container(
                          margin: EdgeInsets.fromLTRB(0,0,0,0),
                          // color: Colors.red,
                          child: !widget.readOnly ? Stack(
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.fromLTRB(0,30,0,0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: TextFormField(
                                        controller: widget.controller,                            
                                        autofocus: false,
                                        readOnly: true,
                                        style: TextStyle(
                                          color: Colors.transparent,
                                        ),
                                        decoration: InputDecoration(
                                            // labelText: widget.label,
                                            labelStyle: TextStyle( 
                                                fontSize: 14.0, 
                                                color: Color.fromARGB(255, 93, 93, 93)
                                            ),
                                            enabledBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(width:0.5,color: Colors.grey[500]),
                                            ),
                                            focusedBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(width:0.5,color: Colors.blue),
                                            ),
                                            errorBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(width:0.5,color: Colors.red),
                                            ),                                    
                                        ),
                                        validator: widget.validator ? (value) {
                                          if (value.isEmpty) {
                                            return widget.validatorText;
                                          }
                                          return null;
                                        }:null,
                                      )
                                    )
                                  ],
                                ),
                              )
                            ],
                          ):null,
                        ),


                      ],
                    ),
                  ),

                ]
            )   
          )  
        );
    }  
}


